package com.enzoism.springboot.dive.test;

import com.enzoism.springboot.dive.common.StringUtil;
import org.junit.Test;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;

@PrepareForTest(StringUtil.class)
public class PowerMock02PrivateMethod extends BaseMockitoTest {

    @Mock
    private StringUtil stringUtil2;
    @Test
    public void test私有非静态方法模拟1() throws InvocationTargetException, IllegalAccessException {
        // MOCK-非静态方法
        StringUtil stringUtil = new StringUtil();

        Method isEmptyMethod = PowerMockito.method(StringUtil.class, "isEmptyOrNot", String.class);
        Boolean invokeFlag = (boolean) isEmptyMethod.invoke(stringUtil, "1111");

        // VERIFY-VALUE
        assertEquals("私有非静态方法结果：", false, invokeFlag);

    }
    @Test
    public void testMock私有非静态方法模拟2() throws Exception {
        // MOCK-非静态方法(进行mock的时候，不能使用真实对象)
        StringUtil stringUtil = new StringUtil();

        // MOCK-Mock私有方法
        PowerMockito.doReturn(true).when(stringUtil2,"testEmptyOrNot",anyString());
        // 进行结果获取的时候，可以用mock和真实的对象
        boolean invokeFlag1 = stringUtil.isEmptyOrNot("1111");
        boolean invokeFlag2 = stringUtil2.isEmptyOrNot("1111");

        // VERIFY-VALUE
        assertEquals("私有静态方法结果：", false, invokeFlag1);
        assertEquals("私有静态方法结果：", false, invokeFlag2);

    }
    @Test
    public void test私有静态方法模拟3() throws InvocationTargetException, IllegalAccessException {
        // MOCK-静态方法
        Method isEmptyMethod = PowerMockito.method(StringUtil.class, "isEmpty", String.class);
        PowerMockito.mockStatic(StringUtil.class);

        Boolean invokeFlag = (boolean) isEmptyMethod.invoke(StringUtil.class, "1111");

        // VERIFY-VALUE
        assertEquals("私有静态方法结果：", false, invokeFlag);

    }
}
